import axios from "axios";
import {ElMessage} from "element-plus";
import qs from 'qs';
const instance =axios.create({
    baseURL: 'http://localhost:8080/boss',
    timeout: 5000,
})
function doGet(path,parameters) {
    return instance({
        url: path,
        method: 'GET',
        params: parameters
    })
}
function doPost(path,parameters) {
    return instance({
        url: path,
        method: 'POST',
        data: parameters
    })
}
function doPostParams(path,parameters) {
    return instance({
        url: path,
        method: 'POST',
        data: qs.stringify(parameters)
    })
}
function doPut(path,parameters) {
    return instance({
        url: path,
        method: 'PUT',
        data: parameters
    })
}
function doDelete(path,parameters) {
    return instance({
        url: path,
        method: 'DELETE',
        params: parameters
    })
}
//声明请求拦截器，增加 jwt 和 operatorId
instance.interceptors.request.use(
    (request) => {
        const sessionJson = window.sessionStorage.getItem('BOSS_TOKEN');
        if(sessionJson){
            const sessionObject = JSON.parse(sessionJson);
            request.headers.Authorization='Bearer '+sessionObject.jwt;
            request.headers.operatorId=sessionObject.operatorId;
        }
        return request;
    },error => {
        console.log(error);
    }
)
//使用拦截器获取服务器返回结果， 对大于1000的code做出错误处理
instance.interceptors.response.use(
    (response) => {
        if(response){
            let code =response.data.code;
            if(code>1000){
                ElMessage.warning(response.data.msg);
                if(code===1006){
                    window.location.href="/login";
                }
            }
        }
        return response;
    },error => {
        console.log(error);
    }
)
export {doGet,doPost,doPut,doDelete,doPostParams};